import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:qunaimedical/models/area.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/values/urls.dart';

typedef Callback<T> = void Function(T value);

class CitySelector extends StatefulWidget {
  /// 返回选择的地区名字和Area对象
  final Callback<List> callback;

  const CitySelector({Key key, @required this.callback}) : super(key: key);

  @override
  _CitySelectorState createState() => _CitySelectorState();
}

class _CitySelectorState extends State<CitySelector> {
  /// 已选的地区索引
  List<int> _selectedAreaIndex = [-1, -1];

  /// 地区列表
  List<Area> _areaList = [];

  /// 分组后的地区列表数据
  Map<Area, List<Area>> areaSets = {};

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return areaSets.isEmpty
        ? SafeArea(child: CupertinoActivityIndicator())
        : SafeArea(
            child: Row(
              children: [
                // 省
                Expanded(
                  child: ListView.separated(
                    itemBuilder: (c, i) {
                      return InkWell(
                        onTap: () {
                          setState(() {
                            _selectedAreaIndex[0] = i;
                            _selectedAreaIndex[1] = -1;
                            widget.callback([
                              areaSets.keys
                                  .toList()[_selectedAreaIndex[0]]
                                  .name,
                              areaSets.keys.toList()[_selectedAreaIndex[0]]
                            ]);
                          });
                        },
                        child: Container(
                          child: Text(
                            '${areaSets.keys.toList()[i].name}',
                            style: TextStyle(
                              color: i == _selectedAreaIndex[0]
                                  ? Theme.of(context).primaryColor
                                  : Colors.black87,
                            ),
                          ),
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.symmetric(horizontal: 16),
                          height: 50,
                        ),
                      );
                    },
                    itemCount: areaSets.keys.length,
                    separatorBuilder: (BuildContext context, int index) =>
                        Divider(),
                    padding: EdgeInsets.all(0),
                  ),
                ),
                VerticalDivider(),
                // 市
                Expanded(
                  child: ListView.separated(
                    itemBuilder: (c, i) {
                      return InkWell(
                        onTap: () {
                          setState(() {
                            _selectedAreaIndex[1] = i;
                            widget.callback([
                              '${areaSets.keys.toList()[_selectedAreaIndex[0]].name}${areaSets[areaSets.keys.toList()[_selectedAreaIndex[0]]][_selectedAreaIndex[1]].name}',
                              areaSets[areaSets.keys
                                      .toList()[_selectedAreaIndex[0]]]
                                  [_selectedAreaIndex[1]],
                            ]);
                          });
                        },
                        child: Container(
                          height: 50,
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.symmetric(horizontal: 16),
                          child: Text(
                            '${areaSets[areaSets.keys.toList()[_selectedAreaIndex[0] == -1 ? 0 : _selectedAreaIndex[0]]][i].name}',
                            style: TextStyle(
                              color: i == _selectedAreaIndex[1]
                                  ? Theme.of(context).primaryColor
                                  : Colors.black87,
                            ),
                          ),
                        ),
                      );
                    },
                    itemCount: areaSets[areaSets.keys.toList()[
                            _selectedAreaIndex[0] == -1
                                ? 0
                                : _selectedAreaIndex[0]]]
                        .length,
                    separatorBuilder: (BuildContext context, int index) =>
                        Divider(),
                    padding: EdgeInsets.all(0),
                  ),
                ),
              ],
            ),
          );
  }

  void _fetchData() async {
    var value = await XHttp.get(Urls.AREA_LIST);
    if (value != null) {
      ListResponse response = ListResponse.fromJson(value);
      if (response.code == 1) {
        _areaList = List.from(response.data.map((e) => Area.fromJson(e)));
        _areaList.removeWhere((element) => element.type == '1');
        _areaList.forEach((element) {
          if (element.type == '2') {
            List<Area> cities = [];
            _areaList.forEach((element1) {
              if (element1.type == '3' && element1.parentId == element.id) {
                cities.add(element1);
              }
            });
            areaSets[element] = cities;
          }
        });
        setState(() {});
      }
    }
  }
}
